﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using GameSchool.Models;
using GameSchool.ViewModels;
using GameSchool.Views.ViewModels;


namespace GameSchool.Controllers
{
    public class VideoController : Controller
    {
		LevelRepository levelRep = new LevelRepository();
		VideoRepository videoRep = new VideoRepository();
		GameRepository grep = new GameRepository();
		CommentRepository cRep = new CommentRepository();

        public ActionResult Index()
        {
			if (User.IsInRole("Admin"))
			{
				var items = from n in videoRep.Videos()
							orderby n.ID ascending
							select n;
				return View(items);
			}
			else
			{
				return RedirectToAction("Games", "Game");
			}
        }

		[HttpGet]
		[Authorize(Roles = "Admin, Teacher")]
		public ActionResult CreateVideo(int? id)
		{
			if (id.HasValue)
			{
				// Senda gameId í viewið
				ViewData["currGame"] = id;
				var game = ((from n in grep.Games()
							 where n.ID == id
							 select n).SingleOrDefault()).Name;

				ViewData["gameName"] = game;

				// Finna öll borð sem tilheyra þessum leik
				var levels = (from n in levelRep.Levels()
							  where n.GameID == id
							  select n);

				// Og senda þau svo í selectlista sem verður birtur í dropdown-lista í viewinu
				ViewData["listOfLevels"] = new SelectList(levels, "ID", "Title");

				TempData["currUrl"] = ("/Video/CreateVideo/" + id).ToString();
				return View(new Video());
			}
			else
			{
				return RedirectToAction("Index","Home");
			}
		}


		[HttpPost]
		[Authorize(Roles = "Admin, Teacher")]
		public ActionResult createVideo(FormCollection formData)
		{
			Video newVideo = new Video();
			videoRep.Add(newVideo);
			UpdateModel(newVideo);
			videoRep.Save();
			return Redirect("../.." + TempData["currUrl"]);
		}


		public ActionResult viewVideo(int? id)
		{
			VideoRepository vRep = new VideoRepository();

			var model = new ViewVideoViewModel()
			{
				Video = (from n in vRep.Videos()
						where n.ID == id.Value
						select n).SingleOrDefault(),
				
				Comments = from n in cRep.Comments()
						   orderby n.Date descending
						   where n.VideoID == id.Value
						   select n
			};
			return View(model);
		}
    }
}
